package utils

import (
	"errors"
	"net"
	"os"
	"os/exec"
	"path/filepath"
	"syscall"
	"time"
)

func CheckPorts(ports []string) error {
	for _, port := range ports {
		conn, err := net.DialTimeout("tcp", "0.0.0.0:"+port, 3*time.Second)
		if err == nil {
			_ = conn.Close()
			return errors.New(port)
		}
	}
	return nil
}

func DiskUsage(path string) (uint64, uint64) {
	fs := syscall.Statfs_t{}
	err := syscall.Statfs(path, &fs)
	if err != nil {
		return 0, 0
	}
	all := fs.Blocks * uint64(fs.Bsize)
	free := fs.Bfree * uint64(fs.Bsize)
	return all, free
}

func ExecPath() (string, error) {
	file, err := exec.LookPath(os.Args[0])
	if err != nil {
		return "", err
	}
	return filepath.Abs(file)
}
